package com.bestillet.kyllingogco;

import java.io.IOException;
import java.io.InputStream;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class CustomerActivity extends Activity {
    public static final String PROPERTY_REG_ID = "registration_id";
    
	private SharedPreferences preferences;
	private EditText name, phone, email;
	private Spinner spinner;
	private Context context;
	private Button ok;

	private RegistrationTask task;
	private ShopApplication app;
	private LoadingDialog loading;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.customer);
		
		this.context = this;
		app = (ShopApplication) getApplicationContext();
		preferences = context.getSharedPreferences("Kylling & Co", MODE_PRIVATE);
		
		String[] s = new String[app.getShops().size()];
		for (int i = 0; i < app.getShops().size(); i++)
			s[i] = app.getShops().get(i).getName();
		
		name = (EditText) findViewById(R.id.txtCustomerName);
		name.setText(preferences.getString("name", ""));
		
		phone = (EditText) findViewById(R.id.txtCustomerPhone);
		phone.setText(preferences.getString("phone", ""));
		
		email = (EditText) findViewById(R.id.txtCustomerEmail);
		email.setText(preferences.getString("email", ""));
		
		ok = (Button) findViewById(R.id.btnCustomerDone);
		ok.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String n = name.getText().toString();
				String p = phone.getText().toString();
				String e = email.getText().toString();
				
				if (p.length() != 8) {
					Toast.makeText(context, context.getResources().getString(R.string.error_checkout_cellphone_digits), Toast.LENGTH_LONG).show();
				} else if (n.length() > 0 && p.length() > 0 && e.length() > 0) {
					loading = new LoadingDialog(context);
					loading.show();
					
					Editor editor = preferences.edit();
					editor.putString("name", n);
					editor.putString("phone", p);
					editor.putString("email", e);
					editor.putInt("shopId", app.getShops().get(spinner.getSelectedItemPosition()).getIdx());
					editor.commit();
					
					task = new RegistrationTask();
					task.execute();
				} else
					Toast.makeText(context, context.getResources().getString(R.string.error_customer_info), Toast.LENGTH_LONG).show();
				}
			});

		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(context, android.R.layout.simple_spinner_item, s);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		spinner = (Spinner) findViewById(R.id.shop);
		spinner.setAdapter(adapter);
		
		int shopId = preferences.getInt("shopId", -1);
		int i = 0;
		boolean found = false;
		while (!found && i < app.getShops().size()) {
			if (shopId == app.getShops().get(i).getIdx())
				found = true;
			else
				i++;
		}
		if (found)
			spinner.setSelection(i);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (task != null)
			if (task.getStatus() == Status.RUNNING)
				task.cancel(true);
	}
	
	@Override
	public void onBackPressed() { }
	
	private class RegistrationTask extends AsyncTask<Void, Void, Boolean> {
    	@Override
		protected Boolean doInBackground(Void... params) {
			try {
				String regid = preferences.getString(PROPERTY_REG_ID, "");
				String phone = preferences.getString("phone", "");
				int shopId = preferences.getInt("shopId", 150);
				InputStream in = Server.post(Server.REGISTER, Server.getAuthenticationNotification(regid, phone, shopId, app.getKundeId()));
				XmlPullParser parser = Server.toXmlParser(in);
				int idx = XmlParser.getNotificationId(parser);
				return (idx == -1);
			} catch (IOException e) {
    			Log.e("Shop", "IOException: " + e.getMessage());
    			return false;
    		} catch (XmlPullParserException e) {
    			Log.e("Shop", "XmlPullParserException: " + e.getMessage());
    			return false;
    		} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
    			return false;
    		} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
    	}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	if (!success) {
		    	Editor editor = preferences.edit();
				editor.remove(PROPERTY_REG_ID);
				editor.commit();
		    }
	    	loading.dismiss();
    		finish();
	    }
	}
}
